package com.david.mydemo.ctl_webservice;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.service.model.BindingInfo;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.xml.namespace.QName;
import java.nio.charset.Charset;

@Slf4j
public class WebServiceClient {

    public static String invokeCheckAiuapTokenWsApi(String wsUrl, String xmlParam) {
        //请求体
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(wsUrl);
        try {
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", "");
            StringEntity data = new StringEntity(xmlParam, Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                // 打印响应内容
                retStr = EntityUtils.toString(httpEntity, "UTF-8");
                log.info("调用4A单点登陆统一认证接口返回结果：{}", retStr);
                retStr = StringEscapeUtils.unescapeXml(retStr);
                retStr = "<USERRSP>" + retStr.split("<USERRSP>")[1].split("</USERRSP>")[0] + "</USERRSP>";
            }
            // 释放资源
            closeableHttpClient.close();
        } catch (Exception e) {
            log.error("调用4A单点登陆统一认证接口报错，错误信息：", e);
        }
        return retStr;
    }

    public static String invokeUpdateAppAcctWsApi(String wsUrl, String xmlParam) {
        JaxWsProxyFactoryBean bean = new JaxWsProxyFactoryBean();
        bean.setServiceClass(UserInfoWebService.class);
        bean.setAddress(wsUrl);
        UserInfoWebService userInfoWebService = (UserInfoWebService) bean.create();
        String result = userInfoWebService.UpdateAppAcctSoap(xmlParam);
//        log.info("接口返回参数：{}", result);
        return result;
    }

    /**
     * 调用WebService接口
     *
     * @param wsUrl    ws地址
     * @param method   方法
     * @param xmlParam 参数
     * @return 处理结果
     */
    public static Object invokeWsApi(String wsUrl, String method, Object xmlParam) {
        try {
            JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
            Client client = factory.createClient(wsUrl);
            Endpoint endpoint = client.getEndpoint();
            QName opName = new QName(endpoint.getService().getName().getNamespaceURI(), method);
            BindingInfo bindingInfo = endpoint.getEndpointInfo().getBinding();
            if (bindingInfo.getOperation(opName) == null) {
                for (BindingOperationInfo operationInfo : bindingInfo.getOperations()) {
                    if (method.equals(operationInfo.getName().getLocalPart())) {
                        opName = operationInfo.getName();
                        break;
                    }
                }
            }
            // 可以在此处配置入拦截器或者出拦截器
            // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
            Object[] objects = client.invoke(opName, xmlParam);
            log.info("调用webService接口返回数据：{}", objects[0]);
            return objects[0];
        } catch (Exception e) {
            log.error("调用webService接口报错，错误信息：", e);
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        String wsUrl = "http://localhost:7090/webservice/userWebService?wsdl";
        // add、delete、change、chgstatus、resetpwd
        String method = "UpdateAppAcctSoap";
        String xmlParam = "<?xml version='1.0' encoding='UTF-8'?>" +
                "<USERMODIFYREQ><HEAD>" +
                "<CODE>0</CODE><SID>0</SID><TIMESTAMP>20240702103917</TIMESTAMP><SERVICEID>GSNGGIS</SERVICEID></HEAD>" +
                "<BODY><OPERATORID>admin</OPERATORID><OPERATORIP>127.0.0.1</OPERATORIP><MODIFYMODE>add</MODIFYMODE>" +
                "<USERINFO><USERID></USERID><LOGINNO>menglijuanGIS</LOGINNO><USERNAME>孟丽娟</USERNAME><ORGID>10000</ORGID><EMAIL>18894022699@139.com</EMAIL><MOBILE>18894022699</MOBILE><PASSWORD>16|-125|67|51|-64|50|112|-64|104|22|-49|50|-1|-5|86|-64|89</PASSWORD><STATUS>1</STATUS><EFFECTDATE>2024-07-02 10:38:52</EFFECTDATE><EXPIREDATE>2050-01-13 00:00:00</EXPIREDATE><REMARK></REMARK>" +
                "</USERINFO>" +
                "</BODY></USERMODIFYREQ>";
//        Object result = invokeWsApi(wsUrl, method, xmlParam);
        String result = invokeUpdateAppAcctWsApi(wsUrl, xmlParam);
        log.info(JSONObject.toJSONString(result));

//        String xml = "<?xml version='1.0' encoding='UTF-8'?>" +
//                "<USERINFO>" +
//                "<USERID>1</USERID>" +
//                "<USERACCOUNT>zhangsan</USERACCOUNT>" +
//                "<USERPW>123456</USERPW>" +
//                "<USERNAME>张三</USERNAME>" +
//                "<USERAGE>33</USERAGE>" +
//                "<USERSEX>男</USERSEX>" +
//                "</USERINFO>";
//        log.info(JSONObject.toJSONString(XmlParserUtil.parseFromXml(xml, WsUserInfo.class)));

//        UserModifyResponseInfo userModifyResponseInfo = new UserModifyResponseInfo();
//        UserModifyRspHead userModifyRspHead = new UserModifyRspHead();
////        userModifyRspHead.setCode("000");
////        userModifyRspHead.setSid("000");
//        userModifyRspHead.setTimestamp(DateUtils.dateTimeNow());
//        userModifyRspHead.setServiceid("hxtt");
//        userModifyResponseInfo.setUserModifyRspHead(userModifyRspHead);
//        UserModifyRspBody userModifyRspBody = new UserModifyRspBody();
//        userModifyRspBody.setRsp("1");
//        userModifyRspBody.setKey("zhangsan");
//        userModifyRspBody.setErrCode("zhangsan");
//        userModifyRspBody.setErrDesc("");
//        userModifyResponseInfo.setUserModifyRspBody(userModifyRspBody);
//
//        log.info(XmlParserUtil.parse2Xml(userModifyResponseInfo, UserModifyResponseInfo.class));
    }

}
